<template>
  <div>
    <van-popup v-model="visible" :position="position" :closeable="type == 'buy' ? true : false" :style="{ height, width: '100%', 'pointer-events': 'auto' }">
      <div class="prescription-info-container">
        <div class="header">
          <a
            v-if="type == ''"
            @click="closeClick"
            href="javascript:;"
            class="btn-back">
            <span class="icon-back"></span>
          </a>
          <span>{{headerTitle}}</span>
        </div>
        <div class="content-container">
          <div class="tips">
            <p>以下信息用于合作的互联网诊疗机构为您提供问诊开方服务。为了您的健康，请准确、完整添加用药人及与用药相关的已确诊疾病信息。</p>
            <p>本次操作视为您已进行过初诊诊断。</p>
          </div>
          <div class="content">
            <div class="medicine-man-container">
              <div class="title">请选择用药人</div>
              <div class="medicine-man-wrapper">
                <div 
                  :class="['medicine-man', selected_medical_patient_id == item.id ? 'selected':'']" 
                  v-for="(item,index) in medicine_man_list" 
                  :key="index"
                  @click="selectMedicineMen(item)"
                >
                  <div class="personal-info">
                    <div class="name">{{ item.real_name }}</div>
                    <div>
                      <span class="gender">{{ item.f_gender }}</span>
                      <span class="age">{{ item.age }}岁</span>
                    </div>
                  </div>
                  <div class="operation">
                    <div @click.stop="addMedicineMan(item)">编辑</div>
                    <div @click.stop="removeMedicineMan(item.id)">删除</div>
                  </div>
                </div>
                <div class="add-medicine-man" @click="addMedicineMan(false)">+</div>
              </div>
            </div>
            <div class="adaptation-disease-container">
              <div class="title">本次用药相关的已确诊疾病（可多选）</div>
              <div class="adaptation-disease-wrapper">
                <div 
                  :class="['adaptation-disease',  item.selected ? 'selected':'']" 
                  v-for="(item, index) in adaptation_diseases" 
                  :key="index" 
                  @click="selectAdaptationDisease(index)"
                >{{ item.name }}</div>
                <!-- <div class="add-adaptation-disease" @click="addDisease">＋</div> -->
              </div>
            </div>
          </div>
        </div>
        <div class="msettlement_sub">
          <div class="btn gra-btn" @click="saveDisease">保存并同意问诊</div>
          <div class="btn return-btn" @click="closeClick">返回</div>
        </div>
      </div>
    </van-popup>
    <!-- 添加已确诊疾病 -->
    <van-popup 
      v-model="show_add_disease" 
      position="bottom"
      :round="true"
      :closeable="true"
      :style="{ height: '40%' }" 
      class="add_disease"
    >
      <div class="title">添加疾病</div>
      <div class="input-cell">
        <input type="text" placeholder="添加疾病" v-model="add_disease">
      </div>
      <div class="btn-add-disease" @click="diseaseAddBtn">添加</div>
    </van-popup>
    <!-- 添加用药人 -->
    <medicine-man
      :headerTitle="title"
      :height="height"
      :position="position"
      :visible="show_add_medicine_man"
      :medicalPatientData="medicalPatientData"
      :prescription_consultation_dz="prescription_consultation_dz"
      :relation="relation"
      @close="closeAddMedicineMan"
      @save="getMedicalPatientList"
    />
  </div>
</template>

<script>
  import Vue from 'vue'
  import { Popup, Dialog } from 'vant'
  Vue.use(Popup)

  import medicineMan from './medicineMan.vue'
  import { MedicalPatientList, MedicalPatientsaveDisease, MedicalPatientDelete } from '@/api/dz/dzPrescriptionDrug'

  export default {
    name: 'index',
    components: {
      medicineMan
    },
    data() {
      return {
        prescription_consultation_dz: 0, // 第三方问诊插件开关
        medicine_man_list: [], // 用药人列表
        selected_medical_patient_id: 0, //  选中的用药人
        bf_adaptation_diseases: [], // 保存之前的疾病列表
        adaptation_diseases: [], // 疾病列表
        show_add_disease: false, // 添加疾病弹层
        add_disease: '',
        show_add_medicine_man: false, // 添加用药人
        medicalPatientData: {}, // 用药人信息
        disease_history: {}, // 默认疾病史
        title: '添加用药人',
        relation: []
      }
    },
    props: {
      visible: {
        type: Boolean,
        default: true
      },
      medicalPatientId: {
        default: 0
      },
      medicalPatientItemId: {
        default: 0
      },
      headerTitle: {
        type: String,
        default: '请完善用药人信息'
      },
      height: {
        type: String,
        default: '100%'
      },
      position: {
        type: String,
        default: 'right'
      },
      type: {
        type: String,
        default: ''
      }
    },
    mounted() {
    },
    watch: {
      visible(val) {
        if (val) {
          this.selected_medical_patient_id = this.medicalPatientId
          this.init()
        }
      }
    },
    methods: {
      init() {
        this.getMedicalPatientList()
      },
      // 用药人列表
      getMedicalPatientList() {
        this.$loadingWrap.show()
        const sendData = {
          item_id: this.medicalPatientItemId
        }
        MedicalPatientList(sendData).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            this.prescription_consultation_dz = res.data.prescription_consultation_dz
            this.medicine_man_list = res.data.patient
            this.disease_history = res.data.disease_history
            this.relation = res.data.relation
            this.adaptation_diseases = res.data.disease || []
            this.bf_adaptation_diseases = res.data.disease || []
            if (this.selected_medical_patient_id) {
              this.selectMedicineMen(res.data.patient.filter(item => item.id == this.selected_medical_patient_id)[0])
              // this.adaptation_diseases = res.data.patient.filter(item => item.id == this.selected_medical_patient_id)[0].disease
            }
          } else {
            this.$Error(res.msg)
          }
        })
      },
      // 选择用药人
      selectMedicineMen(item) {
        this.selected_medical_patient_id = item.id
        // this.adaptation_diseases = item.disease
        const disease = item.disease.filter(item => item.selected == 1)
        const newList = JSON.parse(JSON.stringify(this.bf_adaptation_diseases))
        for (const i in disease) {
          for (const j in newList) {
            if (disease[i].name == newList[j].name) {
              if (disease[i].selected == 1) {
                newList[j].selected = 1
              }
            }
          }
        }
        this.adaptation_diseases = newList
      },
      // 选择已确诊疾病
      selectAdaptationDisease(index) {
        this.adaptation_diseases[index].selected = this.adaptation_diseases[index].selected ? 0 : 1
      },
      // 添加/编辑用药人
      addMedicineMan(item) {
        this.show_add_medicine_man = true
        if (item) {
          this.title = '编辑用药人'
          this.medicalPatientData = {
            relation: item.relation, // 关系 id
            relation_name: item.relation_name, // 关系名称
            id: item.id, // 用药人id
            item_id: this.medicalPatientItemId, // 商品id
            real_name: item.real_name, // 真实姓名
            id_no: item.id_no, // 身份证号
            birthday: item.f_birthday, // 出身年月
            gender: item.gender, // 	性别(1:男 2:女)
            phone: item.phone, // 	手机号
            past_medical_history_status: item.past_medical_history_status, // 过往病史状态(1: 2:无)
            past_medical_history: item.past_medical_history || [], // 	过往病史
            allergic_history_status: item.allergic_history_status, // 	过敏史状态(1:有 2:无)
            allergic_history: item.allergic_history || [], // 	过敏史
            family_medical_history_status: item.family_medical_history_status, // 	家族病史状态(1:有 2:无)
            family_medical_history: item.family_medical_history || [], // 	家族病史
            liver_function: item.liver_function, // 	肝功能(1:正常 2:异常)
            renal_function: item.renal_function, // 	肾功能(1:正常 2:异常)
            pregnancy_and_lactation: item.pregnancy_and_lactation, // 妊娠哺乳(1:有 2:无)
            pregnancy_status: item.pregnancy_status // 	妊娠状态(1:备孕中 2:怀孕中 3:正在哺乳)
          }
        } else {
          this.title = '添加用药人'
          this.medicalPatientData = {
            relation: '', // 关系 id
            relation_name: '请选择关系', // 关系名称
            item_id: this.medicalPatientItemId, // 商品id
            real_name: '', // 真实姓名
            id_no: '', // 身份证号
            birthday: '', // 出身年月
            gender: 1, // 	性别(1:男 2:女)
            phone: '', // 	手机号
            past_medical_history_status: 2, // 过往病史状态(1: 2:无)
            past_medical_history: this.disease_history.past_medical_history || [], // 	过往病史
            allergic_history_status: 2, // 	过敏史状态(1:有 2:无)
            allergic_history: this.disease_history.allergic_history || [], // 	过敏史
            family_medical_history_status: 2, // 	家族病史状态(1:有 2:无)
            family_medical_history: this.disease_history.family_medical_history || [], // 	家族病史
            liver_function: 1, // 	肝功能(1:正常 2:异常)
            renal_function: 1, // 	肾功能(1:正常 2:异常)
            pregnancy_and_lactation: 2, // 妊娠哺乳(1:有 2:无)
            pregnancy_status: [
              {
                name: '备孕中',
                selected: 0
              }, {
                name: '怀孕中',
                selected: 0
              }, {
                name: '正在哺乳',
                selected: 0
              }
            ] // 	妊娠状态(1:备孕中 2:怀孕中 3:正在哺乳)
          }
        }
      },
      closeAddMedicineMan() {
        this.show_add_medicine_man = false
      },
      // 删除用药人
      removeMedicineMan(id) {
        Dialog.confirm({
          message: '确定删除？',
          className: 'common-confirm',
          closeOnClickOverlay: true,
          confirmButtonText: '确定'
        }).then(() => {
          this.$loadingWrap.show()
          MedicalPatientDelete({ id: id }).then(res => {
            if (res.status == 1) {
              if (id == this.selected_medical_patient_id) {
                this.selected_medical_patient_id = 0
                this.$emit('saveClick', this.selected_medical_patient_id)
              }
              this.$Error('删除成功')
              this.getMedicalPatientList()
            } else {
              this.$loadingWrap.close()
              this.$Error(res.msg)
            }
          })
          // on confirm
        }).catch(() => {
          // on cancel
        })
      },
      // 添加疾病
      addDisease() {
        // this.show_add_disease = true
        this.add_disease = ''
      },
      diseaseAddBtn() {
        if (this.add_disease) {
          const reg = /^([\u4e00-\u9fa5]|[a-zA-Z0-9_\-\\\/])+$/
          if (!reg.test(this.add_disease.trim())) {
            this.$Error('只允许输入数字字母下划线')
          } else if (this.adaptation_diseases.some(item => item.name === this.add_disease)) {
            this.$Error('不能添加重复的疾病')
          } else {
            this.show_add_disease = false
            this.adaptation_diseases.push({
              name: this.add_disease,
              selected: 1
            })
          }
        } else {
          this.$Error('请添加疾病')
        }
      },
      // 保存并同意问诊
      saveDisease() {
        if (this.selected_medical_patient_id == 0) {
          this.$Error('请选择用药人')
          return false
        }
        if (!this.adaptation_diseases.some(item => item.selected == 1)) {
          this.$Error('请选择已确诊的疾病')
          return false
        }
        const sendData = {
          id: this.selected_medical_patient_id,
          item_id: this.medicalPatientItemId,
          disease: JSON.stringify(this.adaptation_diseases)
        }
        this.$loadingWrap.show()
        MedicalPatientsaveDisease(sendData).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            this.$emit('saveClick', this.selected_medical_patient_id)
            this.closeClick()
          } else {
            this.$Error(res.msg)
          }
        })
      },
      closeClick() {
        this.selected_medical_patient_id = 0
        this.$emit('closeClick')
      }
    }
  }
</script>

<style lang="scss">
.prescription-info-container {
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  overflow: auto;
  padding: 100px 0 80px;
  box-sizing: border-box;
  .header {
    width: 100%;
    height: 100px;
    position: absolute;
    left: 0;
    top: 0;
    line-height: 94px;
    background: #fff;
    border-bottom: 2px solid #f5f5f5;
    text-align: center;
    .btn-back {
      position: absolute;
      left: 0;
      top: 0;
      display: block;
      width: 80px;
      height: 94px;
      padding-top: 4px;
      .icon-back{
        border: solid #666;
        border-width: 0 3px 3px 0;
        display: inline-block;
        padding: 8px;
        transform: rotate(135deg);
        -webkit-transform: rotate(135deg);
      }
    }
    .btn-close {
      position: absolute;
      right: 0;
      top: 0;
      display: block;
      width: 80px;
      height: 94px;
      padding-top: 4px;
    }
    .icon-backg {
      font-size: 40px;
    }
    span {
      font-size: 32px;
    }
  }
  .content-container {
    margin: 20px;
    padding: 20px 30px 40px;
    background: #fff;
    .tips {
      color: #aaa;
      font-size: 24px;
      line-height: 40px;
    }
    .content {
      margin-top: 40px;
      .medicine-man-container {
        .title {
          font-size: 32px;
          color: #000;
        }
        .medicine-man-wrapper {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          .medicine-man {
            width: 280px;
            height: 160px;
            border: solid 1px #bbb;
            border-radius: 24px;
            margin-top: 30px;
            display: flex;
            justify-content: space-between;
            color: #999;
            padding: 20px;
            margin-right: 40px;
            &.selected {
              border-color: #FE5500;
              color: #FE5500;
            }
            .name {
              font-size: 32px;
              font-weight: 600;
              overflow: hidden;
              word-break: break-all;
              -webkit-line-clamp: 2;
              line-clamp: 2;
              -webkit-box-orient: vertical;
              box-orient: vertical;
              display: -webkit-box;
              display: box;
            }
            .gender, .age {
              display: inline-block;
              font-size: 24px;
              margin-top: 14px;
              margin-right: 10px;
            }
            .operation {
              flex-shrink: 0;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
            }
          }
          .add-medicine-man {
            width: 280px;
            height: 160px;
            border: dashed 1px #bbb;
            border-radius: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 150px;
            margin-top: 30px;
            color: #bbb;
          }
        }
      }
      .adaptation-disease-container {
        margin-top: 40px;
        .title {
          font-size: 32px;
          color: #000;
          margin-bottom: 30px;
        }
        .adaptation-disease-wrapper {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          .adaptation-disease {
            line-height: 52px;
            font-size: 28px;
            padding: 0px 24px;
            border: solid #999 2px;
            border-radius: 50px;
            margin-right: 20px;
            margin-bottom: 15px;
            &.selected {
              border-color: #FE5500;
              color: #FE5500;
            }
          }
          .add-adaptation-disease {
            height: 52px;
            line-height: 52px;
            font-size: 45px;
            padding: 0px 30px;
            background: #eee;
            border-radius: 50px;
            color: #aaa;
            margin-bottom: 15px;
          }
        }
      }
    }
  }
  .msettlement_sub {
    position: absolute;
    display: flex;
    .btn {
      flex: 1;
      line-height: 72px;
      color: #fff;
      font-size: 32px;
      font-weight: bold;
      text-align: center;
      &.return-btn {
        border-radius: 0px 50px 50px 0;
        background: rgb(254, 147, 3);
      }
      &.gra-btn {
        border-radius: 50px 0 0 50px;
        background: #FE5500;
      }
    }
  }
}
.add_disease {
  padding: 0 12px;
  .title {
    font-size: 32px;
    color: #333;
    line-height: 100px;
    text-align: center;
    border-bottom: solid 1px #e5e5e5;
    font-weight: 600;
  }
  .input-cell {
    height: 80px;
    border-bottom: solid 1px #e5e5e5;
    input {
      width: 100%;
      height: 100%;
      font-size: 28px;
      padding-left: 20px;
      box-sizing: border-box;
    }
  }
  .btn-add-disease {
    width: 90%;
    // height: 70px;
    position: absolute;
    padding: 11px 30px;
    left: 50%;
    border-radius: 40px;
    background: #FE5500;
    text-align: center;
    color: #fff;
    line-height: 70px;
    transform: translateX(-50%);
    font-size: 32px;
    bottom: constant(safe-area-inset-bottom);
    bottom: env(safe-area-inset-bottom);
  }
}
</style>